import { Component, OnInit, ViewChild, Inject } from '@angular/core';
import { NgForm, FormBuilder, FormControl, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { markAllAsTouched } from 'app/modules/base/helper';
import { ToasterService } from '../../../share/services/toaster.service';
import { Router } from '@angular/router';
import { WhitelistService, WhiteList } from '../../services/whitelist.service';

@Component({
  selector: 'm-whitelist-add',
  templateUrl: './whitelist-add.component.html',
  styleUrls: ['./whitelist-add.component.scss']
})
export class WhitelistAddComponent implements OnInit {

  @ViewChild(NgForm) ngForm: NgForm;
  submitting: boolean = false;
  today = new Date();
  formGroup = this.fb.group({
    id: 0,
    alias_name: new FormControl('', Validators.required),
    authorization: 1,
    remarks: [''],
    remaining_date: {
      year: this.today.getFullYear(),
      month: this.today.getMonth() + 1,
      day: this.today.getDate(),
      hour: 0,
      minutes: 0
    },
    permanent: false
  })
  constructor(
    public dialogRef: MatDialogRef<WhitelistAddComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    public fb: FormBuilder,
    private service: WhitelistService,
    private toaster: ToasterService,
    private router: Router,
    ) { }

  ngOnInit() {
  }

  async create() {
    markAllAsTouched(this.formGroup);
    if (this.formGroup.invalid) {
      return;
    }

    const data: WhiteList = {};
    const remaining_date = this.formGroup.get('remaining_date').value;
    data.alias_name = this.formGroup.get('alias_name').value;
    data.authorization = Number(this.formGroup.get('authorization').value);
    data.remarks = this.formGroup.get('remarks').value;
    if (remaining_date) {
      data.remaining_date = new Date(
        remaining_date.year, 
        remaining_date.month - 1, 
        remaining_date.day).toISOString();
    } else {
      delete data['remaining_date'];
    }
    const resp: any = await this.service.addWhitelist(this.data.id, data);
    this.toaster.success('成功');
    this.cancel();
    this.router.navigateByUrl(`usb-device/whitelist/${data['alias_name']}?id=${resp.id}`)
  }

  cancel() {
    this.dialogRef.close();    
  }

  permanent() {
    if (this.formGroup.get('permanent').value) {
      const remaining_date = this.formGroup.get('remaining_date');
      remaining_date.disable();
      remaining_date.reset();
    } else {
      const remaining_date = {
        year: this.today.getFullYear(),
        month: this.today.getMonth() + 1,
        day: this.today.getDate(),
        hour: 0,
        minutes: 0
      }
      this.formGroup.get('remaining_date').enable();
      this.formGroup.get('remaining_date').setValue(remaining_date);
    }
  }
}
